<template>
	<div class="box">
		<div class="input-box">
			<el-form
				ref="formRef"
				style="max-width: 600px"
				:model="ruleForm"
				:rules="rules"
				label-width="auto"
				class="demo-ruleForm"
				status-icon
				label-position="left"
			>
				<el-form-item label="用户名" prop="username">
					<el-input v-model="ruleForm.username" clearable />
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input type="password" v-model="ruleForm.password" clearable />
				</el-form-item>
				<el-form-item>
					<el-button style="width: 100%" type="primary" @click="submitForm(formRef)">登录</el-button>
				</el-form-item>
			</el-form>
		</div>
	</div>
</template>

<script setup lang="ts">
	import { reactive, ref } from 'vue'
	import { ElMessage, FormInstance, FormRules } from 'element-plus'
	import { useRouter } from 'vue-router'
	import { Login } from '@/api/userApi.ts'

	interface RuleForm {
		username: string
		password: string
	}
	const formRef = ref<FormInstance>()
	// zhang 88888888
	const ruleForm = reactive<RuleForm>({
		username: '',
		password: '',
	})
	const rules = reactive<FormRules<RuleForm>>({
		username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
		password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
	})
	const router = useRouter()

	const submitForm = (formEl: FormInstance | undefined) => {
		if (!formEl) return
		formEl.validate(async (valid) => {
			if (valid) {
				const res = await Login(ruleForm.username, ruleForm.password)
				if (res.code == 401) {
					ElMessage({
						type: 'error',
						message: res.message,
					})
				} else {
					ElMessage({
						type: 'success',
						message: '登录成功',
					})
					localStorage.setItem('username', ruleForm.username)
					router.push('back')
				}
			} else {
				console.log('error submit!')
			}
		})
	}
</script>

<style scoped lang="scss">
	.box {
		padding: 20px;
		.input-box {
			margin: 50px auto;
			width: 600px;
			height: 600px;
		}
	}
</style>
